import type React from 'react'
import { createContext, useContext, useState } from 'react'
import type { Theme, ThemeName } from './themes'
import { defaultTheme, themes } from './themes'

export interface ThemeContextValue {
  theme: Theme
  themeName: ThemeName
  setTheme: (themeName: ThemeName) => void
}

const ThemeContext = createContext<ThemeContextValue | undefined>(undefined)

export interface ThemeProviderProps {
  children: React.ReactNode
  theme?: ThemeName
  setTheme?: (themeName: ThemeName) => void
}

export const ThemeProvider: React.FC<ThemeProviderProps> = ({
  children,
  theme: initialTheme = 'pink',
  setTheme: externalSetTheme,
}) => {
  const [internalThemeName, setInternalThemeName] = useState<ThemeName>(initialTheme)
  
  const theme = themes[internalThemeName] || defaultTheme

  const handleSetTheme = (newThemeName: ThemeName) => {
    setInternalThemeName(newThemeName)
    if (externalSetTheme) {
      externalSetTheme(newThemeName)
    }
  }

  const contextValue: ThemeContextValue = {
    theme,
    themeName: internalThemeName,
    setTheme: handleSetTheme,
  }

  return <ThemeContext.Provider value={contextValue}>{children}</ThemeContext.Provider>
}

export const useTheme = (): ThemeContextValue => {
  const context = useContext(ThemeContext)
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider')
  }
  return context
}

export { ThemeContext }
